<template>
  <div class="trashbin-container">
	  <el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	          <el-col :span="24" class="text-center">
	              <div class="title-wrapper">
	              <i class="el-icon-search el-icon--large"></i>
	              <h1 class="main-title">垃圾堆叠信息管理系统</h1>
	              <p class="sub-title">实时追踪垃圾桶满溢情况，及时调度清运服务，每一次细致管理，都是为了让社区环境更清爽、生活更舒心</p>
	              </div>
	          </el-col>
	      </el-row>
    <!-- 详情对话框 -->
   <!-- <el-dialog
      v-model="dialogVisible"
      title="垃圾桶详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="垃圾桶信息" direction="vertical" :column="4" :model="currentTrashBin" border>
        <el-descriptions-item label="垃圾桶ID" :span="2">{{ currentTrashBin.binId }}</el-descriptions-item>
        <el-descriptions-item label="位置ID" :span="2">{{ currentTrashBin.locationId }}</el-descriptions-item>
        <el-descriptions-item label="垃圾桶类型" :span="2">{{ currentTrashBin.binType }}</el-descriptions-item>
        <el-descriptions-item label="容量" :span="2">{{ currentTrashBin.capacity }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="4">{{ currentTrashBin.status }}</el-descriptions-item>
        <el-descriptions-item label="位置名称" :span="4">{{ currentTrashBin.locationName || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="最后更新时间" :span="4">{{ currentTrashBin.lastUpdate || '无记录' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>-->

        <el-dialog
          v-model="dialogVisible"
          title="详情"
          width="70%">
          <el-row :gutter="20">
            <el-col :span="12">
              <Yibiao :Capacity="currentTrashBin.capacity" />
            </el-col>
            <el-col :span="12">
              <el-form :model="currentTrashBin" label-width="100px" class="demo-ruleForm">
                <el-form-item label="ID">
                  <el-input v-model="currentTrashBin.binId" disabled></el-input>
                </el-form-item>
                <el-form-item label="位置">
                  <el-input v-model="currentTrashBin.locationId" disabled></el-input>
                </el-form-item>
                <el-form-item label="垃圾桶类型">
                  <el-input v-model="currentTrashBin.binType" disabled></el-input>
                </el-form-item>
                <el-form-item label="容量">
                  <el-input v-model="currentTrashBin.capacity" disabled></el-input>
                </el-form-item>
                <el-form-item label="最近检查日期">
                  <el-input v-model="currentTrashBin.lastUpdate" disabled></el-input>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑垃圾桶信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="垃圾桶ID" prop="binId" disabled>
          <el-input v-model="editForm.binId"></el-input>
        </el-form-item>
        <el-form-item label="位置ID" prop="locationId">
          <el-input v-model.number="editForm.locationId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="垃圾桶类型" prop="binType">
          <el-select v-model="editForm.binType" placeholder="请选择垃圾桶类型">
            <el-option label="可回收物" value="可回收物"></el-option>
            <el-option label="厨余垃圾" value="厨余垃圾"></el-option>
            <el-option label="有害垃圾" value="有害垃圾"></el-option>
            <el-option label="其他垃圾" value="其他垃圾"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input v-model.number="editForm.capacity" type="number" placeholder="请输入容量值，大于0"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="Operational" value="Operational"></el-option>
            <el-option label="Maintenance" value="Maintenance"></el-option>
            <el-option label="Full" value="Full"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增垃圾桶信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="垃圾桶ID" prop="binId">
          <el-input v-model="addForm.binId" placeholder="例如: LJ000001"></el-input>
        </el-form-item>
        <el-form-item label="位置ID" prop="locationId">
          <el-input v-model.number="addForm.locationId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="垃圾桶类型" prop="binType">
          <el-select v-model="addForm.binType" placeholder="请选择垃圾桶类型">
            <el-option label="可回收物" value="可回收物"></el-option>
            <el-option label="厨余垃圾" value="厨余垃圾"></el-option>
            <el-option label="有害垃圾" value="有害垃圾"></el-option>
            <el-option label="其他垃圾" value="其他垃圾"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input v-model.number="addForm.capacity" type="number" placeholder="请输入容量值，大于0"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="Operational" value="Operational"></el-option>
            <el-option label="Maintenance" value="Maintenance"></el-option>
            <el-option label="Full" value="Full"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input 
            placeholder="输入垃圾桶ID进行查询" 
            v-model="searchId" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-input 
            placeholder="输入位置名称进行查询" 
            v-model="searchLocationName" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="searchStatus" 
            placeholder="按状态筛选" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="Operational" value="Operational"></el-option>
            <el-option label="Maintenance" value="Maintenance"></el-option>
            <el-option label="Full" value="Full"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="binId" label="垃圾桶ID" width="120" align="center"></el-table-column>
        <el-table-column prop="locationId" label="位置ID" width="100" align="center"></el-table-column>
        <el-table-column prop="locationName" label="位置名称" width="180" align="center"></el-table-column>
        <el-table-column prop="binType" label="垃圾桶类型" width="120" align="center"></el-table-column>
        <el-table-column prop="capacity" label="容量" width="100" align="center"></el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdate" label="最后更新时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" @click="openDetailDialog(scope.row)">
                <i class="el-icon-view"></i> 查看
              </el-button>
              <el-button type="warning" size="mini" @click="openEditDialog(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="danger" size="mini" @click="deleteTrashBin(scope.row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<!-- 脚本部分保持不变 -->
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import Yibiao from "./Yibiao.vue";

// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)


// 搜索条件
const searchId = ref('')
const searchLocationName = ref('')
const searchStatus = ref('')


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)


// 数据存储
const trashBinList = ref([])
const filteredData = ref([])


// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)


// 当前选中的垃圾桶信息
const currentTrashBin = reactive({
  binId: '',
  binType: '',
  locationId: null,
  capacity: null,
  status: '',
  locationName: '',
  lastUpdate: ''
})


// 编辑表单数据
const editForm = reactive({
  binId: '',
  binType: '',
  locationId: null,
  capacity: null,
  status: ''
})


// 新增表单数据
const addForm = reactive({
  binId: '',
  binType: '',
  locationId: null,
  capacity: null,
  status: ''
})


// 表单验证规则
const rules = reactive({
  binId: [
    { required: true, message: '请输入垃圾桶ID', trigger: 'blur' }
    // 移除了格式验证的正则表达式规则
  ],
  locationId: [
    { required: true, message: '请输入位置ID', trigger: 'blur' },
    { type: 'number', message: '位置ID必须为数字', trigger: 'blur' }
  ],
  binType: [
    { required: true, message: '请选择垃圾桶类型', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入容量', trigger: 'blur' },
    { type: 'number', message: '容量必须为数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error('容量必须大于0'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})



// 根据状态获取标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case 'Operational': return 'success'
    case 'Full': return 'warning'
    case 'Maintenance': return 'info'
    default: return ''
  }
}


// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  Object.assign(currentTrashBin, row)
}


// 打开编辑对话框
function openEditDialog(row) {
  editDialogVisible.value = true
  Object.assign(editForm, {
    binId: row.binId,
    binType: row.binType,
    locationId: row.locationId,
    capacity: row.capacity,
    status: row.status
  })
}


// 打开新增对话框
function openAddDialog() {
 addDialogVisible.value = true
   if (addFormRef.value) {
     addFormRef.value.resetFields()
   }
   addForm.binType = ''
   addForm.status = 'Operational' // 设置默认状态为Operational
}


// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '更新中...' })
    post('/sc/trashbin/updateById', editForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchTrashBinList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}


// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/trashbin/add', addForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchTrashBinList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}


// 删除垃圾桶信息
function deleteTrashBin(row) {
  ElMessageBox.confirm(`确定删除垃圾桶 ${row.binId} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/trashbin/deleteById', { binId: row.binId }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchTrashBinList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}


// 搜索处理
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  // 如果输入了位置名称，调用后端接口搜索
  if (searchLocationName.value) {
    post('/sc/trashbin/getByLocationName', { locationName: searchLocationName.value }, (res) => {
      loading.close()
      if (res && res.data) {
        filteredData.value = res.data
      } else if (Array.isArray(res)) {
        filteredData.value = res
      } else {
        filteredData.value = []
      }
      
      showSearchResultMessage()
    })
  } else {
    // 否则使用本地数据过滤
    filteredData.value = trashBinList.value.filter(item => {
      const matchesId = !searchId.value || item.binId.includes(searchId.value)
      const matchesStatus = !searchStatus.value || item.status === searchStatus.value
      return matchesId && matchesStatus
    })
    
    loading.close()
    showSearchResultMessage()
  }
  
  currentPage.value = 1 // 重置到第一页
}

// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}


// 重置搜索
function resetSearch() {
  searchId.value = ''
  searchLocationName.value = ''
  searchStatus.value = ''
  filteredData.value = [...trashBinList.value]
  currentPage.value = 1
}


// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}



// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}


// 获取所有垃圾桶信息
function fetchTrashBinList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/trashbin/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      trashBinList.value = res.data
      filteredData.value = [...res.data]
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      trashBinList.value = []
      filteredData.value = []
    }
  })
}


// 页面加载时获取数据
onMounted(() => {
  fetchTrashBinList()
})
</script>

<style scoped>
.trashbin-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}


.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}


.el-table {
  margin-top: 20px;
}


.el-pagination {
  margin-top: 20px;
}


.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}


.el-form {
  padding: 10px;
}
</style>
